package cn.lzwei.bilimall.product.service.impl;

import cn.lzwei.bilimall.product.entity.CategoryBrandRelationEntity;
import cn.lzwei.bilimall.product.service.CategoryBrandRelationService;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.lzwei.common.utils.PageUtils;
import cn.lzwei.common.utils.Query;

import cn.lzwei.bilimall.product.dao.CategoryDao;
import cn.lzwei.bilimall.product.entity.CategoryEntity;
import cn.lzwei.bilimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Resource
    CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询所有分类以及子分类，以树形结构组装起来
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查询所有分类数据
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //2.以树形结构组装分类数据
        List<CategoryEntity> collect = entities.stream().filter(item ->
            //2.1 返回一级分类
            item.getParentCid()==0
        ).map(item->{
            //2.2 递归找出子分类
            item.setChildren(getChildrens(item,entities));
            return item;
        }).sorted((item1,item2)->{
            //3.一级分类排序
            return (item1.getSort() == null ? 0 : item1.getSort())-(item2.getSort() == null ? 0 : item2.getSort());
        }).collect(Collectors.toList());

        return collect;
    }
    //递归找出当前分类的子分类，并返回当前分类
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> data){
        return data.stream().filter(item -> item.getParentCid().equals(root.getCatId())).map(item->{
            item.setChildren(getChildrens(item,data));
            return item;
        }).sorted((item1,item2)->{
            //2.3 子分类排序
            return (item1.getSort() == null ? 0 : item1.getSort())-(item2.getSort() == null ? 0 : item2.getSort());
        }).collect(Collectors.toList());
    }

    /**
     * 逻辑删除分类数据
     * @RequestBody 获取请求体的内容，要求发送 POST 请求
     * Spring MVC 会将请求体的内容转换成对应类型
     */
    @Override
    public void removeMenuByIds(Long[] catIds) {
        //TODO 检查当前删除的菜单，是否被别的地方引用
        //逻辑删除：配置逻辑
        baseMapper.deleteBatchIds(Arrays.asList(catIds));
    }

    /**
     * 属性分组：获取分类路径
     * @param catelogId
     * @return
     */
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> result=new ArrayList<>();
        findParentPath(catelogId, result);
        Collections.reverse(result);
        return result.toArray(new Long[result.size()]);
    }
    //递归获取分类路径
    private void findParentPath(Long catelogId,List<Long> result){
        result.add(catelogId);
        CategoryEntity category = baseMapper.selectById(catelogId);
        if (!category.getParentCid().equals(0l)){
            findParentPath(category.getParentCid(),result);
        }
    }

    /**
     * 分类修改：并更新在其他表中的冗余字段
     */
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        //1.更新 品牌分类关联表
        Long catId = category.getCatId();
        String name = category.getName();
        categoryBrandRelationService.updateCategory(catId,name);
        //TODO 分类修改：更新在其他表中的冗余字段
    }

}